package dao.impl;
import	java.util.ArrayList;

import com.alibaba.druid.util.StringUtils;
import dao.AdminDao;
import model.po.Admin;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminDaoImpl implements AdminDao {

    /**
     * 获取Admin对象，以传入的Admin对象的id，email依次作为条件从数据库中查找对应的Admin信息，需要在调用前new一个Admin对象并设置成员变量的值
     * @param admin 传入的Admin对象
     * @return 从数据库中查找到的Admin，返回值可能为空
     */
    @Override
    public Admin getAdmin(Admin admin) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String condition = null; //where后面的条件
        String parameter = null; //prepared statement的参数

        if (null != admin.getId()) {
            condition = "`id` = ?";
            parameter = String.valueOf(admin.getId());
        } else if (null != admin.getEmail()) {
            condition = "`email` = ?";
            parameter = admin.getEmail();
        } else if (null != admin.getNickname()) {
            condition = "`nickname` = ?";
            parameter = admin.getNickname();
        }
        if (null == condition || null == parameter) {
            return null;
        }

        String sql = "select * from `admin` where " + condition;
        Admin adminFromDb = null;
        try {
            adminFromDb = queryRunner.query(sql, new BeanHandler<>(Admin.class), parameter);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return adminFromDb;
    }

    /**
     * 获取数据库中全部管理员账户的信息
     * @return 包含全部管理员账户的List，返回值可能为空
     */
    @Override
    public List<Admin> getAllAdmins() {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<Admin> allAdmins = null;
        String sql = "select * from `admin`";
        try {
            allAdmins = runner.query(sql, new BeanListHandler<>(Admin.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return allAdmins;
    }

    @Override
    public int deleteAdmin(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "delete from `admin` where `id` = ?";
        int result = 0;
        try {
            result = runner.update(sql, id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int getAdminsNumber() {
        int number = 0;
        try (Connection connection = DruidUtils.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as `number` from `admin`");
            ResultSet resultSet = preparedStatement.executeQuery();
            resultSet.next();
            number = resultSet.getInt("number");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return number;
    }

    @Override
    public int changePwd(Admin admin) {
        int result = 0;
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "update `admin` set `pwd` = ? where `nickname` = ?";
        try {
            result = queryRunner.update(sql, admin.getPwd(), admin.getNickname());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int updateAdmin(Admin admin) {
        int result = 0;
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "update `admin` set `nickname` = ?, `email` = ?, `pwd` = ? where `id` = ?";
        try {
            result = queryRunner.update(sql, admin.getNickname(), admin.getEmail(), admin.getPwd(), admin.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int addAdmin(Admin admin) {
        int result = 0;
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "insert into `admin` values (null, ?, ?, ?)";
        try {
            result = queryRunner.update(sql, admin.getEmail(), admin.getPwd(), admin.getNickname());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public List<Admin> getSearchAdmins(Admin admin) {
        Map<String, Object> map = getDynamicSql(admin);
        String sql = (String)map.get("sql");
        List<String> parameters = (List<String>)map.get("parameters");
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());

        List<Admin> adminList = null;
        try {
            adminList = queryRunner.query(sql, new BeanListHandler<>(Admin.class), parameters.toArray());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return adminList;
    }



    //Private Methods

    private Map<String, Object> getDynamicSql(Admin admin) {
        String base = "select * from `admin` where 1 = 1 ";
        List<String> parameters = new ArrayList<>();
        if (!StringUtils.isEmpty(admin.getEmail())) {
            base += "and `email` like ? ";
            parameters.add("%" + admin.getEmail() + "%");
        }
        if (!StringUtils.isEmpty(admin.getNickname())) {
            base += "and `nickname` like ? ";
            parameters.add("%" + admin.getNickname() + "%");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("sql", base);
        map.put("parameters", parameters);
        return map;
    }
}
